//系统逻辑及业务相关通用函数库 iview

import Cookies from "js-cookie";
import { forEach, hasOneOf } from "@/libs/tools";

export const TOKEN_KEY = "token";

//通用
export const getSessionStore = key => {
  let str = sessionStorage.getItem(key);
  return str;
};

export const setSessionStore = (key, value) => {
  sessionStorage.setItem(key, value);
};

//通用
export const getSessionObjStore = key => {
  let str = sessionStorage.getItem(key);
  if (str) {
    return JSON.parse(str);
  } else {
    return null;
  }
};

export const setSessionObjStore = (key, value) => {
  sessionStorage.setItem(key, JSON.stringify(value));
};

//cookie str
export const setCookie = (key, value) => {
  //Cookies.set(key, value, {domain: window.location.host});
  //相同域名不同端口，用于多站区分cookie，cookie是不会区分端口的
  key = window.location.host + "-" + key;
  Cookies.set(key, value);
};

export const getCookie = key => {
  key = window.location.host + "-" + key;
  let value = Cookies.get(key);
  if (value) return value;
  else return null;
};

//cookie Obj
export const setCookieObj = (key, value) => {
  let data = value;
  if (value) {
    data = JSON.stringify(value);
  }
  setCookie(key, data);
};

export const getCookieObj = key => {
  let value = getCookie(key);
  if (value) {
    return JSON.parse(value);
  } else {
    return null;
  }
};

export const hasChild = item => {
  return item.children && item.children.length !== 0;
};

const showThisMenuEle = (item, access) => {
  if (item.meta && item.meta.access && item.meta.access.length) {
    if (hasOneOf(item.meta.access, access)) return true;
    else return false;
  } else return true;
};
/**
 * @param {Array} list 通过路由列表得到菜单列表
 * @returns {Array}
 */
export const getMenuByRouter = (list, access) => {
  let res = [];
  forEach(list, item => {
    if (!item.meta || (item.meta && !item.meta.hideInMenu)) {
      let obj = {
        icon: (item.meta && item.meta.icon) || "",
        name: item.name,
        meta: item.meta
      };
      if (
        (hasChild(item) || (item.meta && item.meta.showAlways)) &&
        showThisMenuEle(item, access)
      ) {
        obj.children = getMenuByRouter(item.children, access);
      }
      if (item.meta && item.meta.href) obj.href = item.meta.href;
      if (showThisMenuEle(item, access)) res.push(obj);
    }
  });
  return res;
};

/**
 * @param {Array} routeMetched 当前路由metched
 * @returns {Array}
 */
export const getBreadCrumbList = routeMetched => {
  let res = routeMetched
    .filter(item => {
      return item.meta === undefined || !item.meta.hide;
    })
    .map(item => {
      let obj = {
        icon: (item.meta && item.meta.icon) || "",
        name: item.name,
        meta: item.meta
      };
      return obj;
    });
  res = res.filter(item => {
    return !item.meta.hideInMenu;
  });
  res = res.filter(item => {
    return !item.meta.hideInNav;
  });
  return [
    {
      name: "导航",
      to: ""
    },
    ...res
  ];
};

export const showTitle = (item, vm) =>
  vm.$config.useI18n
    ? vm.$t(item.name)
    : (item.meta && item.meta.title) || item.name;

/**
 * @description 本地存储和获取标签导航列表
 */
export const setTagNavListInLocalstorage = list => {
  sessionStorage.tagNaveList = JSON.stringify(list);
  //localStorage.tagNaveList = JSON.stringify(list);
};
/**
 * @returns {Array} 其中的每个元素只包含路由原信息中的name, path, meta三项
 */
export const getTagNavListFromLocalstorage = () => {
  //const list = localStorage.tagNaveList;
  const list = sessionStorage.tagNaveList;
  return list ? JSON.parse(list) : [];
};

/**
 * @param {Array} routers 路由列表数组
 * @description 用于找到路由列表中name为home的对象
 */
export const getHomeRoute = routers => {
  let i = -1;
  let len = routers.length;
  let homeRoute = {};
  while (++i < len) {
    let item = routers[i];
    if (item.children && item.children.length) {
      let res = getHomeRoute(item.children);
      if (res.name) return res;
    } else {
      if (item.name === "home") homeRoute = item;
    }
  }
  return homeRoute;
};

/**
 * @param {*} list 现有标签导航列表  status代表地第一次加载
 * @param {*} newRoute 新添加的路由原信息对象
 * @description 如果该newRoute已经存在则不再添加
 */
export const getNewTagList = (list, newRoute) => {
  const { name, path, meta } = newRoute;
  let newList = [...list];
  if (newList.findIndex(item => item.name === name) >= 0) {
    return newList;
  } else {
    newList.push({ name, path, meta, status: "init" });
  }
  return newList;
};

/**
 * @param {*} access 用户权限数组，如 ['super_admin', 'admin']
 * @param {*} route 路由列表
 */
const hasAccess = (access, route) => {
  if (route.meta && route.meta.access)
    return hasOneOf(access, route.meta.access);
  else return true;
};

/**
 * 权鉴
 * @param {*} name 即将跳转的路由name
 * @param {*} access 用户权限数组
 * @param {*} routes 路由列表
 * @description 用户是否可跳转到该页
 */
export const canTurnTo = (name, access, routes) => {
  const routePermissionJudge = list => {
    return list.some(item => {
      if (item.children && item.children.length) {
        return routePermissionJudge(item.children);
      } else if (item.name === name) {
        return hasAccess(access, item);
      }
    });
  };

  return routePermissionJudge(routes);
};

/**
 * @param {String} url
 * @description 从URL中解析参数
 */
export const getParams = url => {
  const keyValueArr = url.split("?")[1].split("&");
  let paramObj = {};
  keyValueArr.forEach(item => {
    const keyValue = item.split("=");
    paramObj[keyValue[0]] = keyValue[1];
  });
  return paramObj;
};

/**
 * @param {String} url
 * @description 从URL中解析参数
 */
export const resolveParams = str => {
  const keyValueArr = str.split("&");
  let paramObj = {};
  keyValueArr.forEach(item => {
    const keyValue = item.split("=");
    paramObj[keyValue[0]] = keyValue[1];
  });
  return paramObj;
};

/**
 * @param {Array} list 标签列表
 * @param {String} name 当前关闭的标签的name
 */
export const getNextName = (list, name) => {
  let res = "";
  if (list.length === 2) {
    res = "home";
  } else {
    if (list.findIndex(item => item.name === name) === list.length - 1)
      res = list[list.length - 2].name;
    else res = list[list.findIndex(item => item.name === name) + 1].name;
  }
  return res;
};

/**
 * @param {key} string 注册store
 */
export const regStore = (store, subStore, name) => {
  if (store.state[name]) {
    console.log("The store already exists!");
  } else {
    store.registerModule(name, subStore);
  }
};
